import router from '@/router';
import axios from 'axios'
import { refreshTokenApi } from '@/api/login/index'

const instance = axios.create({
    withCredentials: true,
    baseURL: import.meta.env.VITE_BASE_API,
    timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use((config) => {
    const token = localStorage.getItem("access_token");
    if (config.headers && !config.headers.Authorization && token) {
        config.headers['Authorization'] = token;
    }
    return config;
}, (error) => {
    return Promise.reject(error);
});

let isRefreshing = false
let requests: ((newTokens: string) => void)[] = []
// 添加响应拦截器
instance.interceptors.response.use(async (response) => {
    if (response.data.code === 401) {
        if (!isRefreshing) {
            isRefreshing = true
            try {
                new Promise((resolve) => {
                    requests.push((newTokens: string) => {
                        response.config.headers.Authorization = newTokens;
                        resolve(instance(response.config));
                    });
                });
                const res = await refreshTokenApi()
                if (res.data.access_token) {
                    const data = res.data
                    localStorage.setItem('access_token', `Bearer ${data.access_token}`)
                    localStorage.setItem('refresh_token', data.refresh_token)
                    const access_token = localStorage.getItem("access_token") as string;
                    requests.forEach(cb => cb(access_token))
                    requests.length = 0
                } else {
                    localStorage.removeItem('access_token')
                    localStorage.removeItem('refresh_token')
                    router.push('/login')
                }
            } catch (err) {
                ElNotification({
                    title: '400',
                    message: '长时间未操作，请重新登录',
                    duration: 1000,
                    type: 'error',
                    showClose: false,
                })
                localStorage.removeItem('access_token')
                localStorage.removeItem('refresh_token')
                router.push('/login')
            } finally {
                isRefreshing = false
            }
        } else {
            return new Promise((resolve) => {
                requests.push((newTokens: string) => {
                    response.config.headers.Authorization = newTokens;
                    resolve(instance(response.config));
                });
            });
        }
    }
    return response;
}, async (error) => {
    if (error.response && error.response.status === 401) {
        localStorage.clear()
        router.push('/login')
    }
    if (error.response && error.response.status === 500) {
        ElNotification({
            title: '500',
            message: '远程服务器访问失败',
            duration: 1000,
            type: 'error',
            showClose: false,
        })
    }
    return Promise.reject(error);
});

export default instance
